package com.atguigu.exp;

import com.atguigu.res.ResultCodeEnum;
import com.atguigu.res.ResultData;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice//统一异常处理,表示此类是一个全局异常处理类
public class GlobalExceptionHandler {
    @ExceptionHandler(BusinessException.class)//统一处理业务异常,捕获BusinessException异常
    public ResultData<Integer> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.error("请求:{},业务异常：{}", request.getRequestURL(), e.getMessage(), e);
        return ResultData.fail(e.getCode(), e.getMessage() + "你的请求url: " + request.getRequestURL());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//统一处理运行时异常,为此异常码为500
    public ResultData<Integer> exception(Exception e) {
        System.out.println("运行时异常");
        log.error("全局异常信息:{}", e.getMessage(), e);
        return ResultData.fail(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
    }
}
